package com.soup.lab.spring.web.advice;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.soup.lab.spring.web.tools.enums.ser.EnumCodeSerialize;
import com.soup.lab.spring.web.tools.enums.ser.EnumCodeSerializer;

import java.io.IOException;
import java.util.Collection;
import java.util.List;

public class NullHandledBeanSerializerModifier extends BeanSerializerModifier {

    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
        for (BeanPropertyWriter writer : beanProperties) {
            // EnumCode属性
            EnumCodeSerialize enumCodeSerialize = writer.getAnnotation(EnumCodeSerialize.class);
            if(enumCodeSerialize != null) {
                writer.assignNullSerializer(new EnumCodeSerializer.NullEnumCodeSerializer(writer.getName(), enumCodeSerialize.name()));
                continue;
            }
            Class<?> rawClass = writer.getType().getRawClass();
            // 数组集合类
            if(rawClass.isArray() || Collection.class.isAssignableFrom(rawClass)) {
                writer.assignNullSerializer(NullArrayJsonSerializer.INSTANCE);
                continue;
            }
        }
        return beanProperties;
    }

    public static class NullArrayJsonSerializer extends JsonSerializer {

        public static final JsonSerializer INSTANCE = new NullArrayJsonSerializer();

        @Override
        public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            if(value == null) {
                gen.writeStartArray();
                gen.writeEndArray();
            } else {
                gen.writeObject(value);
            }
        }
    }


}
